package com.db.manage.controller;

import com.db.manage.service.QueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/query")
@RequiredArgsConstructor
public class QueryController {
    private final QueryService queryService;

    @PostMapping("/execute")
    public ResponseEntity<?> executeQuery(
            @RequestParam String connectionId,
            @RequestParam String sql) {
        try {
            log.info("执行查询请求: connectionId={}, sql={}", connectionId, sql);
            List<Map<String, Object>> result = queryService.executeQuery(connectionId, sql);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("执行查询失败: connectionId={}, sql={}", connectionId, sql, e);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            errorResponse.put("message", "执行查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/history")
    public ResponseEntity<List<Map<String, Object>>> getQueryHistory() {
        try {
            List<Map<String, Object>> history = queryService.getQueryHistory();
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            log.error("获取查询历史失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/save")
    public ResponseEntity<String> saveQuery(@RequestBody Map<String, String> query) {
        try {
            queryService.saveQuery(query);
            return ResponseEntity.ok("查询保存成功");
        } catch (Exception e) {
            log.error("保存查询失败", e);
            return ResponseEntity.badRequest().body("查询保存失败: " + e.getMessage());
        }
    }
} 